
var ReportView = View.extend(ReportView = {
    
    collection: null,
    
    init: function() {
        this.setupUI();
        this.loadGroupsAndDates();
        this.collection = new Collection();
        this.setupListeners();
    },
    
    setupListeners: function() {
        var self = this;
        
        App.listen("reportLoaded", function(report_id) {
            $("#print_btn").attr('disabled', true).data('id', report_id);
            $("#export_btn").data('id', report_id);
            $("#export_btn").find("button").attr('disabled', true);
        });
        
        App.listen('reportRendered', function() {
            $("#print_btn").removeAttr('disabled');
            $("#export_btn button").removeAttr('disabled');
        });
        
        App.listen("categoryChanged", function() {
            $("#print_btn").attr('disabled', true);
            $("#export_btn button").attr('disabled', true);
            
            self.runReport();
        });
    },
    
    loadGroupsAndDates: function() {
        var self = this;
        var url = $("#groups_data_url").val();

        $.get(url, function(data) {
            self.renderGroups(data.groups);
            self.renderDates(data.dates);
            
            $("#browser").treeview({
                collapsed: false,
                animated: "fast",
                toggle: function() {
                    //console.log("%s was toggled.", $(this).find(">span").text());
                }
            });

            self.bindReportsList();
            
        }, 'json');
    },
    
    setupUI: function() {
        $("body").on('changed', '#category_select', function(event) {
            var select = event.target;
            var label = $(select).select('selectedItem')['addLabel'];
            var category_id = $(select).select('selectedItem')['value'];
            
            $("#report_member_category_id").val(category_id);
            
            App.notify("categoryChanged", category_id);
        });
    },
    
    renderGroups: function(data) {
        $.each(data, function(k, v) {
            var gtn = v.OrganisationGroupType.name;
            var li = $("<li />").addClass('closed').html("<span>" + gtn + "</span>");
            var ul = $("<ul />");

            for (var i = 0; i < v.OrganisationGroup.length; i++) {
                var group = v.OrganisationGroup[i];
                var url = $("#groups_report_url").val() + "?params[group_id]=" + group.id;
                var gli = $("<li />").html("<span><a title=\"Members In " + group.name + "\" class='report_link' data-id='10' href='" + url + "'>" + group.name + "</a></span>");
                ul.append(gli);
            }

            li.append(ul);

            $("#browser > li").each(function() {
                if ($(this).data("group-name") === "Groups") {
                    $(this).find("ul").first().append(li);
                }
            });
        });
    },
    
    renderDates: function(data) {
        $.each(data, function(k, v) {
            var dtn = v.OrganisationAnniversary.name;
            var url = $("#dates_report_url").val() + "?params[date_id]=" + v.OrganisationAnniversary.id;
            var gli = $("<li />").html("<span><a title=\"Members In " + dtn + "\" class='report_link' data-id='11' href='" + url + "'>" + dtn + "</a></span>");
                
            var ul = null;
            
            $("#browser > li").each(function() {
                if ($(this).data("group-name") === "Dates") {
                    ul = $(this).find("ul").first();
                    return false;
                }
            });
            
            ul.append(gli);
        });
    },
    
    bindReportsList: function() {
        var self = this;

        $(".treeview li a.report_link").click(function(e) {
            e.preventDefault();

            $("a.report_link").removeClass("active");
            $(this).addClass('active');
            $("#report_view .header_el").html($(this).attr("title"));

            var url = $(this).attr("href");
            var report_id = $(this).data('id');
            
            self.loadReport(url, report_id);
        });
    },
    
    loadReport: function(url, report_id) {
        var self = this;

        $("#report_view_holder").html("<div class='wrapper'><div class='alert alert-info'>Loading Report. Please Wait....</div></div>");

        $.post(url, function(data) {
            
            $("#parameters-column").html(data);
            $("#report_view_area").html("");
            $("#report_title").html( "Report: " + $("#report_title_field").val() );            

            self.bindReportActions();

            if ($(".parameter").filter(".list, .number, .string, .date, .datetime").length === 0) {
                $("#generate_btn").click();
            }
            
            // reset report
            self.report = null;
            
            App.notify("reportLoaded", report_id);
        });
    },
    
    bindReportActions: function() {
        var self = this;
        
        $("#generate_btn").click(function() {

            self.runReport();
        });

        $("#settings_btn").click(function(e) {
            e.preventDefault();

            self.showColumnSettings();
        });

        $("#print_btn").click(function(e) {
            e.preventDefault();
            var url = $(this).attr('href') + "/" + $(this).data('id');

            window.open(url, 'printout');
        });
        
        $("#export_btn ul li a").click(function(e) {
            e.preventDefault();
            
            var type = $(this).data('type');
            self.exportReport(type);
        });
    },
    
    runReport: function() {
        var data = {};

        $('.parameter#organisation_member_category_id').val( $("#report_member_category_id").val() );

        $(".parameter").each(function() {
            $(data).attr($(this).data('parameter-name'), $(this).val());
        });
        
        if( Object.keys(data).length == 0 ) {
            //alert("Please select a repo")
            return;
        }

        $("#report_view_area").html("<div class='alert alert-info'>Generating Report. Please Wait ...</div>");

        var url = $("#generate_report_url").val();
        var self = this;

        $.ajax({
            url: url,
            data: data,
            type: 'post',
            dataType: 'json',
            success: function(res) {
                
                self.collection.removeAll();

                for (var i = 0; i < res['Results'].length; i++) {
                    var m = res['Results'][i];
                    var member = new Member(m);

                    self.collection.add(i, member);
                }

                self.report = res;
                self.renderReport();
            },
            error: function(xhr) {
                alert('Failed To Load Report');
                console.log(xhr.responseText);
            }
        });
    },
    
    /**
     * Wrapper function to allow rendering different views for the report
     * 
     * @returns {undefined}
     */
    renderReport: function() {
        if( !this.report ) {
            return;
        }
        
        this.renderTableView();
    },
    
    renderTableView: function() {
        var self = this;
        var report = this.report;
        
        var sbtn = $("<a />").addClass("btn btn-xs btn-white").attr({
            "id": "column_settings",
            "data-toggle": "ajaxModal",
            "href": "/memberz/admin/reports/column_settings"
        }).html("<i class='fa fa-cog'></i>").click(function(e) {
            e.preventDefault();
            self.showColumnSettings();
        });
        
        var table = $("<table />").addClass('table table-condensed table-bordered').attr("id", 'report_table_view');
        
        table.append( 
            $("<thead />").append( 
                $("<tr />").append( 
                    $("<th />").append(sbtn)
                ) 
            ) 
        ).append( 
            $("<tbody />") 
        );
        
        for(var i = 0; i < report.ReportColumn.length; i++) {
            var column = report.ReportColumn[i];
            var dn = column.ReportColumnOption['display_name'];
            var th = $("<th />").html(dn);
            
            table.find("thead tr").append(th);
        }
        
        var count = 1;
        
        self.collection.iterate(function(member) {
            var tr = $("<tr />");
            tr.append( $("<td />").html(count++ + ".").attr("align", "right") );
            
            for(var i = 0; i < report.ReportColumn.length; i++) {
                var td = $("<td />");
                
                try {
                    var type = report.ReportColumn[i].ReportColumnOption['type'];
                    var field = report.ReportColumn[i].ReportColumnOption['field_name'];
                    var value = null;
                    
                    if( field.indexOf(".") > -1 ) {
                        var ps = field.split(".");
                        value = member.get(ps[0])[ps[1]];
                    }

                    else {
                        value = member.get('0')[field];
                    }
                    
                    if( value ) {
                        switch(type) {
                            case 'date':
                                var date = $.datepicker.parseDate("yy-mm-dd", value);
                                value = $.datepicker.formatDate('M d, yy', date);
                                break;
                            case 'datetime':
                                var date = $.datepicker.parseDate("yy-mm-dd", value);
                                value = $.datepicker.formatDate('M d, yy hh:iia', date);
                                break;

                            case 'number':

                                break;

                            default:
                                break;
                        }
                    }

                    td.html(value);
                    
                } catch(e) {
                    //console.log(e);
                }
                
                tr.append(td);
            }
            
            table.find("tbody").append(tr);
        });
        
        $("#report_view_area").html("").append(table);
        
        // notify render complete
        App.notify('reportRendered');
    },
    
    showColumnSettings: function() {
        var self = this;
        var url = $("#search_column_settings_url").val();
        
        $.get(url, function(html) {
            $("#ajaxModal").html(html);
            
            $("#ajaxModal #save_apply").click(function(e) {
                e.preventDefault();
                self.updateReportColumns();
            });
            
            $("#ajaxModal").modal();
        });
    },
    
    updateReportColumns: function() {
        var self = this;
        var columns = [];
        
        $("#ajaxModal input:checked").each(function() {
            var $this = $(this);
            var column = {
                ReportColumnOption: {
                    id: $this.val(),
                    field_name: $this.data('field'),
                    display_name: $this.data('label')
                },
                
                report_column_option_id: $this.val()
            };
            
            columns.push(column);
        });
        
        $("#ajaxModal").modal('hide');
        self.saveColumnSettings(columns);
        
        setTimeout(function() {
            if( self.report ) {
               self.report.ReportColumn = columns;
                self.renderTableView();
            }
        }, 500);
        
    },
    
    saveColumnSettings: function(columns) {
        var url = $("#search_columns_save_url").val();
        var params = {
            columns: columns
        };
        
        $.post(url, params, function() {
            
        });
    },
    
    exportReport: function(type) {
        var url = $("#export_btn").data('url') + "/" + $("#export_btn").data('id') + "/" + type;
        
        window.open(url, 'export');
    }
});

var searchView = null;

$(document).ready(function() {
    searchView = new ReportView();
});
